package com.beta.cat.config.sms;

import com.alibaba.fastjson.JSON;
import com.beta.cat.application.BaseApplication;
import com.beta.cat.config.captcha.CaptchaAutoConfiguration;
import com.beta.cat.utils.RequestParamUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 发送手机验证码，前端是要结合图形验证码的功能
 */
@Slf4j
@RestController
@RequestMapping("${com.beta.sms.url.pre:/sms/code}")
@ConditionalOnProperty(name = "com.beta.sms.verify.enable", havingValue = "true", matchIfMissing = false)
public class SmsVerifyCodeController {
    @Autowired(required = false)
    CaptchaAutoConfiguration.CaptchaCheckService captchaCheckService;
    @Resource
    SmsVerifyService smsVerifyService;

    /**
     * 获取验证码并发送给指定的手机号
     *
     * @param request
     * @param smsReq  验证码相关的信息
     * @return
     */
    @GetMapping(value = "/send", produces = "application/json;charset=utf-8")
    public BaseApplication.ResultVO sendVerifyCode(HttpServletRequest request, SendSmsReq smsReq) {
        log.info("获取手机号验证码:{}", smsReq.getMobile());
        if (smsReq == null
                || org.apache.commons.lang3.StringUtils.isBlank(smsReq.getMobile())
                || !RequestParamUtil.isMobile(smsReq.getMobile())) {
            log.warn("mobile is not valid(请求参数错误), mobile=" + smsReq.getMobile());
            return BaseApplication.ResultVO.failure(1003, "请求参数错误！");
        }
        if (captchaCheckService != null) {
            if (org.apache.commons.lang3.StringUtils.isAnyBlank(smsReq.getCaptcha(), smsReq.getRandStr())) {
                log.warn("captcha info is disappearance(请求参数错误), mobile=" + smsReq.getMobile());
                return BaseApplication.ResultVO.failure(1003, "请求参数错误！");
            }
            boolean succ = captchaCheckService.check(smsReq.getCaptcha(), smsReq.getRandStr());
            if (!succ) {
                log.warn("captcha info is wrong(输入的验证码错误), mobile=" + smsReq.getMobile());
                return BaseApplication.ResultVO.failure(1003, "输入的验证码错误！");
            }
        } else {
            log.warn("captchaCheckService is NULL(系统有问题,请联系管理员), mobile=" + smsReq.getMobile());
            return BaseApplication.ResultVO.failure(1003, "系统有问题,请联系管理员！");
        }
        SmsResult result = smsVerifyService.sendVerifyCode(smsReq.getMobile());
        if (result != null && result.getSuccess() != null && result.getSuccess()) {
            return BaseApplication.ResultVO.success(null);
        } else {
            log.warn("send error, mobile=" + smsReq.getMobile() + "; resultl=" + JSON.toJSONString(result));
            return BaseApplication.ResultVO.failure(1003, StringUtils.defaultIfBlank(result.getMessage(), "获取手机验证码失败！"));
        }
    }

    /**
     * 验证手机的验证码是否正确
     *
     * @param request 前端请求
     * @param smsReq  验证相关的请求
     * @return
     */
    @PostMapping(value = "/verify", produces = "application/json;charset=utf-8")
    public BaseApplication.ResultVO<String> verifyCode(HttpServletRequest request, @RequestBody VerifySmsReq smsReq) {
        if (smsReq == null
                || org.apache.commons.lang3.StringUtils.isBlank(smsReq.getMobile())
                || !RequestParamUtil.isMobile(smsReq.getMobile())) {
            log.warn("mobile is not valid(请求参数错误), smsReq=" + JSON.toJSONString(smsReq));
            return BaseApplication.ResultVO.failure(1003, "请求参数错误！");
        }

        SmsResult result = smsVerifyService.verifyCode(smsReq.getMobile(), smsReq.getCode());
        if (result != null && result.getSuccess() != null && result.getSuccess()) {
            return BaseApplication.ResultVO.success(null);
        } else {
            log.warn("verify ERROR(手机验证码不正确), mobile=" + smsReq.getMobile());
            return BaseApplication.ResultVO.failure(1003, StringUtils.defaultIfBlank(result.getMessage(), "手机验证码不正确！"));
        }
    }

    @Data
    public static class SendSmsReq {
        //手机号
        private String mobile;
        //用户操作输入的图形验证码的值
        private String captcha;
        //图形验证码的随机值
        private String randStr;
    }

    @Data
    public static class VerifySmsReq {
        //手机号
        private String mobile;
        //用户输入的手机验证码
        private String code;
    }
}
